//兼容性语句 gtv:getTempValue stv:setTempValue
if (!this.gtv || this.gtv.toString().indexOf("not supported") > -1) {
  this.gtv = function(key, def) {

    return localStorage[key] || def;

  };
  this.stv = function(key, value) {

    return localStorage[key] = value;

  };
};


{
  //清除不必要的元素
  $("#box-content").css("pointer-events", "none");
  $(".chat,.contact_people,div>a>img,.JobSign").remove();
  $(".Money,img[title=营业执照已验证],img[title=已点亮高保障企业图标]").hide();
}

{
  //初始化图表参数
  let myChart;
  let $chart = $('<div id="chart" />');
  const chartOption = {
    title: {
      text: ''
    },
    tooltip: {},
    legend: {
      data: ['数量']
    },
    xAxis: {
      data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    },
    yAxis: {},
    series: [{
      name: '数量',
      type: 'bar',
      data: [5, 20, 36, 10, 10, 20]
    }]
  };
  const setChart = ($pill) => {
    const chartLabs = chartOption.xAxis;
    const chartLabNums = chartOption.series[0];
    let numGroup = [];
    let labSums = [];
    $pill.find('li').each(function() {
      let lab = $(this).text().match(/[\u4e00-\u9fa5]{1,}/)[0];
      let num = $(this).text().match(/\d+/)[0];
      labSums.push(lab);
      numGroup.push(num);
    });
    chartLabs.data = labSums;
    chartLabNums.data = numGroup;
    myChart.setOption(chartOption);
  };
  $("#paramBox").append($chart[0]);
  myChart = echarts.init(chart);
  //加载parts网页里的组件
  let $loadDiv = $('<div />');
  let loadPartsUrl = chrome.extension.getURL("dist/html/parts.min.html") + " #load";
  let loadPartsCompleteFun = function() {
    let $me = $(this);
    let $allItems = $('.V1Item');
    let $pills = $me.find('ul.nav.nav-pills');
    let $companyKeyWords = $me.find('#companyKeyWords');
    let $emptyBtn = $me.find('#emptyBtn');
    let labSums = {
      areaGroup: new Set(['揭阳榕城区', '揭阳空港经济区', '揭阳揭东区', '揭阳产业园', '揭阳普宁市']),
      eduGroup: new Set(['不限', '大专以上', '高中以上', '中专以上', '初中以上']),
      sexGroup: new Set(['不限', '男', '女']),
      $areaSum: $me.find('#areaSum'),
      $eduSum: $me.find('#eduSum'),
      $sexSum: $me.find('#sexSum'),
      setLabSum: function($labs, labType) {
        let reg = /[a-zA-Z]+(?=Sum)/;
        let groupName = `${labType}Group`;
        let labSum = this[`$${labType}Sum`];
        labSum.children().remove();
        for (let i of labSums[groupName]) {
          let $li;
          let num = 0;
          // let percent = 0;
          $labs.each(function() {
            if ($(this).text() === i) {
              num += 1;
            }
          });
          // percent = parseInt(num / $labs.length * 100);
          $li = $(`<li><a href="javascript:void(0)">${i}(${num})</a></li>`);
          labSum.append($li);
        }
      }
    };
    const setJobItemDataAndcompletedLabTypeForGroup = ($labs, dataName) => {
      $labs.each(function() {
        let $me = $(this);
        const type = $me.text();
        labSums[`${dataName}Group`].add(type);
        $me.parents('.V1Item').attr(`data-${dataName}`, type);
      });
    };
    const blockJobItem = () => {
      let blockItemNum = 0;
      let $blockItemNum = $('body').find('#searBox b');
      let companyKeyWords = new Set($companyKeyWords.val().split(/[,，\s+]/));
      companyKeyWords.delete('');
      $('.V1Item').each(function() {
        let $me = $(this);
        let name = $me.find('.ent_style1').text();
        for (let word of companyKeyWords) {
          if (name.search(word) != -1) {
            $me.addClass('hide');
            blockItemNum += 1;
            break;
          }
        }
      });
      $blockItemNum.text(blockItemNum);
      stv('kwTemp', [...companyKeyWords].join(','));
    };
    const showSelJobItems = () => {
      let $areaLab = $('span[title=工作地点]');
      setJobItemDataAndcompletedLabTypeForGroup($areaLab, 'area');
      let showedAreas = [];
      labSums.$areaSum.find('.active').each(function() {
        let area = $(this).text().match(/[\u4e00-\u9fa5]{3,}/)[0];
        showedAreas.push(area);
      });
      if (showedAreas.length === 0) {
        $allItems.removeClass('hide');
      } else {
        $allItems.addClass('hide');
        showedAreas.forEach(function(area) {
          $(`.V1Item[data-area=${area}]`).removeClass('hide');
        });
      }
    };
    const setEduSum = () => {
      let $ShowedItems;
      $ShowedItems = $allItems.not('.hide');
      labSums.setLabSum($ShowedItems.find('span[title=学历要求]'), 'edu');
    }

    $pills.click(function() {
      setChart($(this));
    });
    //加载选项组件
    $("#paramBox").append($me.find('#load').children());

    labSums.setLabSum($('span[title=工作地点]'), 'area');
    labSums.$areaSum.find('li').click(function() {
      $(this).toggleClass('active');
      showSelJobItems();
      setEduSum();
      blockJobItem();
    });
    $emptyBtn.click(function() {
      labSums.$areaSum.find('.active').removeClass('active');
      $companyKeyWords.val('');
      $('.V1Item').removeClass('hide');
    });
    $companyKeyWords.keyup(blockJobItem);
    $companyKeyWords.val(gtv('kwTemp'));
    $companyKeyWords.keyup();
    setEduSum();



    {
      let $jobItemSet = $(".V1Item");
      //职位描述内容的id
      let jobDescSelector = "#ctl00_ContentPlaceHolder1_requirement";
      //企业地址的id
      let companyAddrSelector = "#ctl00_ContentPlaceHolder1_plEntContact li:eq(2)>p";
      let sexRequestSelector = ".BasicInfo";
      let selSet = [jobDescSelector, companyAddrSelector, sexRequestSelector];
      let remainLoadingPages = $jobItemSet.length;
      let drag = new Drag("dragE", "职位描述", "<h1>这是内容<h1>");
      let $dragE = $("#dragE");
      const setDragTemp = () => {
        stv("dwt", $dragE.css("width"));
        stv("dht", $dragE.css("height"));
        stv("dtt", $dragE.css("transform"));
      };
      $dragE.find(".head>span").click(function() {
        setDragTemp();
        $dragE.hide();
      });
      const setDragStyleFromTemp = () => {
        $dragE.css({
          "width": gtv("dwt"),
          "height": gtv("dht"),
          "transform": gtv("dtt")
        });
      };
      const showDrag = (title, content) => {
        $dragE.dragTitleElem.nodeValue = title;
        $dragE.find(".body").html(content);
        $dragE.show(100);
      }
      //弹出框标题元素--文本节点
      $dragE.dragTitleElem = document.getElementsByClassName('head')[0].firstChild;
      setDragStyleFromTemp();

      $jobItemSet.each(function() {
        let $container = $("<div/>");
        let $jobItem = $(this);
        let $docLink = $(this).find(".JobName a");
        let $jobLabs = $jobItem.find(".JobInfo:eq(0)");
        let jobName =
          `${$jobItem.find(".JobName a").text()} ${$jobItem.find(".JobName .salaryStyle").text()}`;
        let $loadingPic;
        const insertloadingPic = () => {
          let $loadingPic = $('<img />');
          $loadingPic.attr({
            'src': chrome.extension.getURL("img/loading.jpg"),
            'class': 'loadingPic'
          });
          $loadingPic.prependTo($jobItem);
          return $loadingPic;
        };
        $jobItem.find(".l").removeClass("l")
        $loadingPic = insertloadingPic();
        $container.load(`${$docLink.attr("href")} ${selSet.join(",")}`, loadJobDetailComplete);

        function loadJobDetailComplete() {
          const setSexSum = () => {
            let $ShowedItems = $('.V1Item').not('.hide');
            let $showedLabs = $ShowedItems.find(`span[title=性别要求]`);
            labSums.setLabSum($showedLabs, 'sex');
          };
          const appendNewLabs = () => {
            let sex, age;
            sex = $container.find(`${sexRequestSelector} li:eq(2)`).text().replace(/性别要求：|\n/g, '');
            age = $container.find(`${sexRequestSelector} li:eq(5)`).text().replace(/年龄要求：|\n/g, '');
            $jobLabs.css("width", "450px")
              .append(`<i>|</i><span title='年龄要求'>${age}</span>`)
              .find("span[title=职位类型]").text(sex).attr("title", "性别要求");
          };
          const insertCompanyAddr = () => {
            $container.find("#ctl00_ContentPlaceHolder1_showmap").parent()
              .addClass("companyAddr")
              .insertAfter($jobItem.find(".ent_style1>a")).find("span").css("color", "#000");
          };
          const insertBrowseButton = () => {
            let JobDec;
            JobDec = $container.children(jobDescSelector).html();
            //浏览职位描述按钮
            let $browseJobDec = $("<button />");
            $browseJobDec.attr({
              "type": "button",
              "class": "btn btn-info browseJobDec",
            });
            $browseJobDec.text("浏览职位描述");
            $browseJobDec.prependTo($jobItem);
            $browseJobDec.click(() => {
              showDrag(jobName, `${$jobLabs.text()}<br /><br />${JobDec}`);
            });
          };
          const existJob = () => {
            if ($container.children().length == 0) {
              let $stopRecruitLab = $("<span>此职位已停止招聘</span>");
              $stopRecruitLab.addClass('label label-danger stopRecruitLab');
              $docLink.after($stopRecruitLab);
              return false;
            } else {
              return true;
            }
          };
          $loadingPic.hide();
          if (existJob()) {
            appendNewLabs();
            insertCompanyAddr();
            insertBrowseButton();
          }
          remainLoadingPages -= 1;
          if (remainLoadingPages == 0) {
            setSexSum();
            labSums.$areaSum.find('li').click(function() {
              setSexSum();
            });
            $emptyBtn.click(function() {
              setSexSum();
            });
          }
        }
      });

    }
  };
  $loadDiv.load(loadPartsUrl, loadPartsCompleteFun);
}
